#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
from mod_python import util,Session,Cookie
import string

import time
import sys
reload(sys)
sys.setdefaultencoding('utf8')

__dir__         = os.path.dirname(__file__)

def index_reload(req, user_name, user_id):
	req.content_type = 'text/html'
	body_reload = ''
	f = open( os.path.join(__dir__, 'template/user.html.head'), 'r' )
	user_head= f.read()
	f.close()
	f = open( os.path.join(__dir__, 'template/user.html.welcome'), 'r' )
	user_welcome = f.read()
	f.close()
	f = open( os.path.join(__dir__, 'template/user.html.container'), 'r' )
	user_container= f.read()
	f.close()
	f = open( os.path.join(__dir__, 'template/user.html.tail'), 'r' )
	user_tail = f.read()
	f.close()
	user_container_full = ''
	min_num = 0
	for file in os.listdir(os.path.join(__dir__, 'tmp/' + str(user_id) + '/')):
		if not os.path.isdir(file):
			try:
				num = string.atoi(os.path.basename(file))
				if num < min_num:
					min_num = num

				if num != 0:
					img_path = '/tmp/' + str(user_id) + '/' + str(num)
					user_container_full = user_container_full + user_container % {'img_path':img_path, 'id':num, 'user_id':str(user_id)}
			except:
				continue
	main_pic = ''	
	if min_num != 0 and not os.path.exists(os.path.join(__dir__, 'tmp/' + str(user_id) + '/0')):
		main_pic = '/tmp/' + str(min_num)
	elif os.path.exists(os.path.join(__dir__, 'tmp/' + str(user_id) + '/0')):
		main_pic = '/tmp/' + str(user_id) + '/0'
	else:
		main_pic = '/static/img/main_pic'
		
	body_reload = user_head + user_welcome % {'user_name':user_name } + user_container_full + user_tail % {'main_pic':main_pic}
	return body_reload

def log_out(req):
	sess = Session.Session(req)
	sess.invalidate()
	util.redirect(req, "/index.py")

def index(req):
	sess=Session.Session(req,timeout=3600)
	body = ''
	if  sess.has_key('user_name'):
		user_path = os.path.join(__dir__, 'tmp/'+str(sess['user_id']))
		if not (os.path.isdir(user_path) and os.path.exists(user_path)):
			os.mkdir(user_path)
		body = index_reload(req, sess['user_name'], sess['user_id'])
	else:
		req.content_type = 'text/html'
		f = open( os.path.join(__dir__, 'template/login.html'), 'r' )
		body = f.read()
		f.close()

	return body 
